import type { ObserverOrNext } from '../types/Observable'
import { isFunction } from '../utils/utils'
import { Subscription } from './Subscription'
export class Subscriber extends Subscription {
  destination: any
  isStopped = false; // 完成状态
  constructor(ObserverOrNext: ObserverOrNext) {
    super()
    let observer;
    // 如果只是传入一个next处理函数，内部进行构建Observer对象
    if (isFunction(ObserverOrNext)) {
      observer = {
        next: ObserverOrNext
      }
    } else {
      observer = ObserverOrNext
    }
    this.destination = observer
  }
  next(value: any) {
    if (!this.isStopped) {
      this.destination.next(value)
    }
  }
  complete() {
    if (!this.isStopped) {
      this.isStopped = true
      this.destination.complete?.()
    }
  }
  error(value: any) {
    if (!this.isStopped) {
      this.isStopped = true
      this.destination.error?.(value)
    }
  }
}